<?php

// **************************************************************
// | Name： 星空框架 登录注册相关
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2022-02-17 12:58
// **************************************************************
declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\common\IndexController;
use app\common\model\User as UserModel;
use app\common\controller\Wechatclass;
use app\common\services\JwtServices;
use app\common\services\UserServices;
use app\common\services\SendMsg;
use app\common\services\Lock;
use think\facade\Cache;
use think\facade\Db;

/**
 * @xk 登录注册
 */
class Login extends IndexController
{
    public function getLoginInfo()
    {
        $resultData = [];
        $resultData['login_info'] = config('web_config.login_logo');
        $resultData['is_wechat_login'] = 1;
        $this->result(200, '请求成功', 200, '加载成功', $resultData);
    }
    /**
     * @xk 发送验证码
     * @method                                 sendMsg
     * @param                                  SendMsg $sendMsgServices  [description]
     * @param                                  UserModel $userModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse13:false14:07+080
     */
    public function sendMsg(SendMsg $sendMsgServices, UserModel $userModel)
    {
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            // dump($param);die;
            $act = isset($param['act']) ? $param['act'] : 'register';
            $param['tel'] = trim($param['tel']);
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            switch ($act) {
            case 'register':
              // 获取短信验证码
              Cache::delete('sms_'.$act.'_'.$param['tel']);
              // 注册信息 查看是否已经存在该手机号码
              $check_mobile_result = $userModel->checkMobile($param['tel'], $act);
              if (!$check_mobile_result) {
                  throw new \think\Exception('当前手机号已经存在，请直接登录或更换手机号进行注册', 404);
              }
              $res = $sendMsgServices->sendCode($param['tel'], $act);
              break;
            case 'login':
                // 获取短信验证码
                Cache::delete('sms_'.$act.'_'.$param['tel']);
                // 注册信息 查看是否已经存在该手机号码
                $check_mobile_result = $userModel->checkMobile($param['tel'], $act);
                if (!$check_mobile_result) {
                    $resultData['jumpUrl'] = '/pages/login/login';
                    // throw new \think\Exception('手机号不存在，请先注册', 404);
                }
                $res = $sendMsgServices->sendCode($param['tel'], $act);
                break;
            case 'forget':
              // 获取短信验证码
              Cache::delete('sms_'.$act.'_'.$param['tel']);
              // 注册信息 查看是否已经存在该手机号码
              $check_mobile_result = $userModel->checkMobile($param['tel'], $act, $user_sn);
              if (!$check_mobile_result) {
                  // $resultData['jumpUrl'] = '/pages/login/login';
                  throw new \think\Exception('该手机号未绑定或输入错误请重新输入', 404);
              }
              $res = $sendMsgServices->sendCode($param['tel'], $act);
              break;
            case 'chanagetel':
              // 获取短信验证码
              Cache::delete('sms_'.$act.'_'.$param['tel']);
              // 注册信息 查看是否已经存在该手机号码
              $check_mobile_result = $userModel->checkMobile($param['tel'], 'chanagetel', $user_sn);
              if (!$check_mobile_result) {
                  throw new \think\Exception('手机号不存在，请先注册', 404);
              }
              $res = $sendMsgServices->sendCode($param['tel'], $act);
              break;
            case 'bind':
              if (!$user_sn) {
                  $resultData['jumpUrl'] = '/pages/login/login';
                  throw new \think\Exception("您还没有登录，请先进行登录", 300);
              }
              // 获取短信验证码
              Cache::delete('sms_'.$act.'_'.$param['tel']);
              // 注册信息 查看是否已经存在该手机号码
              $check_mobile_result = $userModel->checkMobile($param['tel'], $act, $user_sn);
              if (!$check_mobile_result) {
                  throw new \think\Exception('当前手机号已经存在，请更换其他手机号进行绑定', 404);
              }
              $res = $sendMsgServices->sendCode($param['tel'], $act);
              break;
          }
            if ('OK' == $res['Code']) {
                $result_code = 200;
                $result_msg = '验证码发送成功';
                $resultData = $res;
            } else {
                $result_code = 404;
                $result_msg = '验证码发送频繁，请稍后再试';
                $resultData = $res;
            }
        } catch (\Exception $e) {
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 手机号登录
     * @method                                 telLogin
     * @param                                  UserModel $userModel  [description]
     * @param                                  JwtServices $jwtServices  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse13:false30:03+080
     */
    public function telLogin(UserModel $userModel, JwtServices $jwtServices, SendMsg $sendMsgServices, UserServices $userServices)
    {
        $param = request()->param();
        $code = 200;
        $msg = '通讯成功';
        $result_code = 200;
        $result_msg = '登录成功';
        $resultData = [];
        // Db::startTrans();
        try {
            $act = isset($param['act']) ? $param['act'] : 'pass_login'; // 前端传递登录方式 pass_login = 密码登录
            $userModel->validate($param, $act); // 手机号登录
            $l_user_sn = (isset($param['share_code'])&&$param['share_code']!='') ? base64_decode($param['share_code']) : '';
            $tel = isset($param['tel']) ? $param['tel'] : '';
            $user_info = $userModel
                        ->where([['tel', '=', $tel]])
                        ->field('`pass`,`pass_key`,`user_sn`,`user_name`,`head_pic`,`tel`,`is_bind`,`is_pass_bind`,`is_wechat_bind`,`is_all_bind`,`status`,`level`,`l_user_sn`')
                        ->find();
            if (!$user_info) {
                // $resultData['jumpUrl'] = '/pages/login/login'; // 跳转到登录页面
                // throw new \think\Exception('手机号不存在，请先使用微信授权进行登录', 300);
                
                // $user_data['head_pic'] = $wechat_info['headimgurl'];
                $user_data['user_name'] =  $tel;
                $user_data['user_sn'] = $userModel->getUserCodeNo(date('Ymd'), 12, 1, 'user_sn');
                $user_data['l_user_sn'] = -1;
                $user_data['l_l_user_sn'] = -1;
                $user_data['l_l_l_user_sn'] = -1;
                $user_data['is_wechat_bind'] = 1;
                $user_data['is_count'] = 1;
                $user_data['tel']=$tel;
                $user_data['is_pass_bind']=0;
                $user_data['create_time']=date('Y-m-d H:i:s');
                $user_data['update_time']=date('Y-m-d H:i:s');
                
                $user_res = DB::name('user')->insert($user_data);
                // var_dump($user_res);die;
                
                
                $user_info = $userModel
                        ->where([['tel', '=', $tel]])
                        ->field('`pass`,`pass_key`,`user_sn`,`user_name`,`head_pic`,`tel`,`is_bind`,`is_pass_bind`,`is_wechat_bind`,`is_all_bind`,`status`,`level`,`l_user_sn`')
                        ->find();
            }
            if (1 != $user_info['status']) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('账户已注销', 404);
            }

            switch ($act) {
              case 'pass_login':
                $pass = makePass($param['pass'], $user_info['pass_key']);
                if ($pass != $user_info['pass']) {
                    throw new \think\Exception('密码错误，请重新输入', 404);
                }
                break;
              case 'captch_login':
                $check_captch_result = $userModel->checkCaptch($param['tel'], 'login', $param['captch']);
                if (!$check_captch_result) {
                    throw new \think\Exception("验证码输入错误，请重新输入", 404);
                }
                $userModel->where([['tel','=',$param['tel']]])->save(['is_bind'=>1]);
                break;
            }
            $user_data = [];
            $from = isset($param['from']) ? $param['from'] : 'android'; //
            $deviceid = isset($param['deviceid']) ? $param['deviceid'] : '';
            if ($deviceid != '') {
                switch ($from) {
                case 'android':
                  $user_data['android_device_id'] = $deviceid;
                  break;
                case 'ios':
                  $user_data['ios_device_id'] = $deviceid;
                  break;
              }
            }

            // 存在当前 unionID
            if ($l_user_sn != '' && $user_info['is_all_bind'] == 0 && $l_user_sn != $user_info['user_sn']
          && $l_user_sn != $user_info['l_user_sn']) {
                $l_user_info = $userModel
                        ->where([['user_sn','=',$l_user_sn]])
                        ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                        ->find();
                if ($l_user_info && $l_user_info['status'] == 1) {
                    $user_data['l_user_sn'] = $l_user_info['user_sn'];
                    $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                    $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                    $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                }
                $userModel->where([['user_sn','=',$user_info['user_sn']]])->find()->save($user_data);
                // 给上级进行通知 确定是本次绑定上级会员了
                // $content = '尊敬的会员您好，会员'.$user_info['user_name'].'成功绑定成为您的下级';
                $content = '尊敬的会员您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                $push_data = [];
                $push_data['create_user_sn'] = $user_info['user_sn'];
                $push_data['user_name'] = $user_info['user_name'];
                $push_data['time'] = $user_data['bind_time'];
                $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                // 开始同步调整 对应保有等级处理
                if ($user_info['l_user_sn'] > 0) {
                    // 原来会员的上级存在
                    $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
                }
                // 判断游客会员等级的增加
                $userServices->syncCheckUp($user_info['user_sn'], $l_user_sn, $user_info['user_sn'], $l_user_sn, $user_info['level'], 'chanageUp');
            }
            $resultData = [];
            $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
            $resultData['is_bind'] = $user_info['is_bind']; // 是否绑定手机号
            $resultData['is_pass_bind'] = $user_info['is_pass_bind']; // 是否绑定密码 没完成密码绑定的需要先进行密码绑定
            $resultData['is_wechat_bind'] = $user_info['is_wechat_bind']; // 是否绑定密码 没完成密码绑
            $resultData['tel'] = $user_info['tel']; // 用户手机号
            $resultData['level'] = $user_info['level'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['head_pic_show'] = getShowUrl($user_info['head_pic']);
            $resultData['user_name'] = $user_info['user_name'];
            
            $jwtService = new JwtServices(['param' => ['user_sn' => $resultData['user_sn'],'be_from'=>$from]]);
            $jwt = $jwtService->issueToken();
            $userModel->where([['user_sn','=',$resultData['user_sn']]])->save(['auth_token'=>$jwt]);
            header('token:'.$jwt);
            $result_code = 200;
            $result_msg = '登录成功';
            // Db::commit(); 
        } catch (\Exception $e) {
            // Db::rollback();
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 会员号登录
     * @method                                      userSnLogin
     * @param                                       UserModel $userModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-17Tfalse15:false10:false47+080
     */
    public function userSnLogin(UserModel $userModel, SendMsg $sendMsgServices, UserServices $userServices)
    {
        $param = request()->param();
        $code = 200;
        $msg = '通讯成功';
        $result_code = 200;
        $result_msg = '登录成功';
        $resultData = [];
        try {
            $act = isset($param['act']) ? $param['act'] : 'userSnLogin'; // 前端传递登录方式 pass_login = 密码登录 captch_login = 验证码登录
            $userModel->validate($param, $act); // 手机号登录
            $l_user_sn = (isset($param['share_code'])&&$param['share_code']!='') ? base64_decode($param['share_code']) : '';
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel
                      ->where([['user_sn', '=', $user_sn]])
                      ->field('`pass`,`pass_key`,`user_sn`,`user_name`,`head_pic`,`tel`,`is_bind`,`is_pass_bind`,`is_wechat_bind`,`is_all_bind`,`status`,`level`,`l_user_sn`')
                      ->find();
            if (!$user_info) {
                // $resultData['jumpUrl'] = '/pages/login/login'; // 跳转到登录页面
                throw new \think\Exception('输入正确的会员号', 404);
            }
            if (1 != $user_info['status']) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('账户已注销', 404);
            }
            $pass = makePass($param['pass'], $user_info['pass_key']);
            if ($pass != $user_info['pass']) {
                throw new \think\Exception('请输入正确的登录密码', 404);
            }
            $user_data = [];
            $from = isset($param['from']) ? $param['from'] : 'android'; //
            $deviceid = isset($param['deviceid']) ? $param['deviceid'] : '';
            if ($deviceid != '') {
                switch ($from) {
                case 'android':
                  $user_data['android_device_id'] = $deviceid;
                  break;
                case 'ios':
                  $user_data['ios_device_id'] = $deviceid;
                  break;
              }
            }
            // 存在当前 unionID
            if ($l_user_sn != '' && $user_info['is_all_bind'] == 0 && $l_user_sn != $user_info['user_sn'] && $l_user_sn != $user_info['l_user_sn']) {
                $l_user_info = $userModel
                      ->where([['user_sn','=',$l_user_sn]])
                      ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                      ->find();
                if ($l_user_info && $l_user_info['status'] == 1) {
                    $user_data['l_user_sn'] = $l_user_info['user_sn'];
                    $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                    $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                    $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                }
                $userModel->where([['user_sn','=',$user_info['user_sn']]])->find()->save($user_data);
                // 给上级进行通知 确定是本次绑定上级会员了
                // $content = '尊敬的会员您好，会员'.$user_info['user_name'].'成功绑定成为您的下级';
                $content = '尊敬的会员您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                $push_data = [];
                $push_data['create_user_sn'] = $user_info['user_sn'];
                $push_data['user_name'] = $user_info['user_name'];
                $push_data['time'] = $user_data['bind_time'];
                $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                // 开始同步调整 对应保有等级处理
                if ($user_info['l_user_sn'] > 0) {
                    // 原来会员的上级存在
                    $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
                }
                // 判断游客会员等级的增加
                $userServices->syncCheckUp($user_info['user_sn'], $l_user_sn, $user_info['user_sn'], $l_user_sn, $user_info['level'], 'chanageUp');
            }
            $resultData = [];
            $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
            $resultData['is_bind'] = $user_info['is_bind']; // 是否绑定手机号
            $resultData['is_pass_bind'] = $user_info['is_pass_bind']; // 是否绑定密码 没完成密码绑定的需要先进行密码绑定
            $resultData['is_wechat_bind'] = $user_info['is_wechat_bind']; // 是否绑定过微信
            $resultData['tel'] = $user_info['tel']; // 用户手机号
            $resultData['level'] = $user_info['level'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['user_name'] = $user_info['user_name'];
            Db::commit();
            $jwtService = new JwtServices(['param' => ['user_sn' => $resultData['user_sn'],'be_from'=>$from]]);
            $jwt = $jwtService->issueToken();
            $userModel->where([['user_sn','=',$resultData['user_sn']]])->save(['auth_token'=>$jwt]);
            header('token:'.$jwt);
            $result_code = 200;
            $result_msg = '会员号密码登录成功';
        } catch (\Exception $e) {
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 密码修改
     * @method                                 passSave
     * @param                                  UserModel $userModel  [description]
     * @param                                  JwtServices $jwtService  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse14:05:false30+080
     */
    public function passSave(UserModel $userModel, JwtServices $jwtService)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'forget'; // 操作方法
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $userModel->validate($param, $act); // 注册信息验证  验证手机号 密码 验证码等
            switch ($act) {
              case 'forget':
                $check_mobile_result = $userModel->checkMobile($param['tel'], $act, $user_sn);
                if (!$check_mobile_result) {
                    throw new \think\Exception('当前手机号不存在无法重置密码', 404);
                }
                $check_captch_result = $userModel->checkCaptch($param['tel'], $act, $param['captch']);
                if (!$check_captch_result) {
                    throw new \think\Exception('验证码已经过期或失效，请重新获取验证', 404);
                }
                // 开始修改密码
                $res = $userModel
                      ->where([['tel', '=', $param['tel']]])
                      ->find()
                      ->save(['pass' => $param['pass'],'next_pass'=>$param['pass'],'is_pass_bind'=>1]);
                break;
              case 'editPass':
                $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`pass_key`,`pass`,`user_id`')->find();
                if (!$user_info) {
                    throw new \think\Exception('用户信息不存在', 404);
                }
                $has_pass = makePass($param['old_pass'], $user_info['pass_key']);
                if ($has_pass != $user_info['pass']) {
                    throw new \think\Exception('原密码输入错误，请重新输入', 404);
                }
                $res = $userModel
                      ->find($user_info['user_id'])
                      ->save(['pass' => $param['pass'],'next_pass'=>$param['pass'],'is_pass_bind'=>1]);
                break;
            }

            $result_code = 200;
            $result_msg = '新密码设置成功，请牢记哦';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 微信登录
     * @method                                 weChatLogin
     * @param                                  UserModel $userModel  [description]
     * @param                                  JwtServices $jwtServices  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse14:07:false44+080
     */
    public function wechatLogin(SendMsg $sendMsgServices, UserModel $userModel, UserServices $userServices)
    {
        // 开始执行微信登录
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        Db::startTrans();
        $lock = (new Lock())->lock(["test"], 6000);
        try {
            if (!$lock) {
                throw new \think\Exception("提交过于频繁，请稍后重试", 404);
            }
            $backurl = isset($param['backurl']) ? $param['backurl'] : 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $wechat_code = isset($param['code']) ? $param['code'] : '';
            $l_user_sn = (isset($param['share_code'])&&$param['share_code']!='') ? base64_decode($param['share_code']) : '';
            $options = [
              'appid' => config('core_config.wechat_config.app_id'), // 填写高级调用功能的app id
              'appsecret' => config('core_config.wechat_config.app_script'), // 填写高级调用功能的密钥
            ];
            $weObj = new Wechatclass($options);
            if ('' == $wechat_code) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $access_token = $weObj->getOauthAccessToken($wechat_code);
            if (!$access_token) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $token = $access_token['access_token'] ? $access_token['access_token'] : '';
            $openid = $access_token['openid'] ? $access_token['openid'] : '';
            $wechat_info = $weObj->getOauthUserinfo($token, $openid); //获取用户信息
            if (!$wechat_info || '' == $wechat_info['openid']) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $user_data = [];
            $from = isset($param['from']) ? $param['from'] : 'android'; //
            $deviceid = isset($param['deviceid']) ? $param['deviceid'] : '';
            if ($deviceid != '') {
                switch ($from) {
                case 'android':
                  $user_data['android_device_id'] = $deviceid;
                  break;
                case 'ios':
                  $user_data['ios_device_id'] = $deviceid;
                  break;
              }
            }
            $user_data['wechat_openId'] = $wechat_info['openid'];
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $wechat_info['headimgurl'];
            $user_data['unionid'] = isset($wechat_info['unionid']) ? $wechat_info['unionid'] : '';
            $user_info = $userModel
                      ->where([['unionid', '=', $wechat_info['unionid']]])
                      ->whereOr([['wechat_openId','=',$wechat_info['openid']]])
                      ->field('`user_sn`,`wechat_app_openId`,`wechat_openId`,`user_name`,`user_id`,`tel`,`is_bind`,`is_pass_bind`,`head_pic`,`is_all_bind`,`is_wechat_bind`,`status`,`level`,`l_user_sn`')
                      ->find();
            $is_show = $user_info ? 1 : 0;
            $is_can_push = 0;
            switch ($is_show) {
              case '1':
                if (1 != $user_info['status']) {
                    $resultData['jumpUrl'] = '/pages/login/login';
                    throw new \think\Exception('账户已注销', 404);
                }
                // 存在当前 unionID 当前会员存在
                if ($l_user_sn != '' && $user_info['is_all_bind'] == 0 && $l_user_sn != $user_info['user_sn'] && $l_user_sn != $user_info['l_user_sn']) {
                    $l_user_info = $userModel
                                  ->where([['user_sn','=',$l_user_sn]])
                                  ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                  ->find();
                    if ($l_user_info && $l_user_info['status'] == 1) {
                        $user_data['l_user_sn'] = $l_user_info['user_sn'];
                        $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                        $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                        $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                        $is_can_push = 1;
                    }
                }
                $user_data['is_wechat_bind'] = 1;
                $user_res = $userModel
                            ->where([['user_sn', '=', $user_info['user_sn']]])
                            ->save($user_data);
                if ($is_can_push == 1) {
                    // 给上级进行通知 确定是本次绑定上级会员了
                    $content = '尊敬的会员您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                    $push_data = [];
                    $push_data['create_user_sn'] = $user_info['user_sn'];
                    $push_data['user_name'] = $user_info['user_name'];
                    $push_data['time'] = $user_data['bind_time'];
                    $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                    // 开始同步调整 对应保有等级处理
                    if ($user_info['l_user_sn'] > 0) {
                        // 原来会员的上级存在
                        $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
                    }
                    // 判断游客会员等级的增加
                    $userServices->syncCheckUp($user_info['user_sn'], $l_user_sn, $user_info['user_sn'], $l_user_sn, $user_info['level'], 'chanageUp');
                }
                $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
                $resultData['is_bind'] = $user_info['is_bind'];
                $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
                $resultData['is_wechat_bind'] = 1;
                $resultData['tel'] = $user_info['tel'];
                $resultData['level'] = $user_info['level'];
                $resultData['is_all_bind'] = $user_info['is_all_bind'];
                $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
                $resultData['user_name'] = $user_info['user_name'];
                break;
              case '0':
                $user_data['head_pic'] = $wechat_info['headimgurl'];
                $user_data['user_name'] =  preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
                $user_data['user_sn'] = $userModel->getUserCodeNo(date('Ymd'), 12, 1, 'user_sn');
                $user_data['l_user_sn'] = -1;
                $user_data['l_l_user_sn'] = -1;
                $user_data['l_l_l_user_sn'] = -1;
                $user_data['is_wechat_bind'] = 1;
                $user_data['is_count'] = 1;
                if ($l_user_sn != '') {
                    $l_user_info = $userModel
                                  ->where([['user_sn','=',$l_user_sn]])
                                  ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                  ->find();
                    if ($l_user_info && $l_user_info['status'] == 1) {
                        $user_data['l_user_sn'] = $l_user_info['user_sn'];
                        $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                        $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                        $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                        $is_can_push = 1;
                    }
                }
                $user_res = $userModel->create($user_data);
                if ($is_can_push == 1) {
                    // 给上级进行通知 确定是本次绑定上级会员了
                    $content = '尊敬的会员您好，您的好友【'.$user_data['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_data['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                    $push_data = [];
                    $push_data['create_user_sn'] = $user_data['user_sn'];
                    $push_data['user_name'] = $user_data['user_name'];
                    $push_data['time'] = $user_data['bind_time'];
                    $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                    // 判断游客会员等级的增加
                    $userServices->syncCheckUp($user_data['user_sn'], $l_user_sn, $user_data['user_sn'], $l_user_sn, 1, 'chanageUp');
                }
                // 新会员注册完成
                $resultData['user_sn'] = $user_data['user_sn']; // 用户编号
                $resultData['is_bind'] = 0;
                $resultData['is_pass_bind'] = 0;
                $resultData['is_all_bind'] = 0;
                $resultData['is_wechat_bind'] = 1;
                $resultData['tel'] = '';
                $resultData['level'] = 1;
                $resultData['head_pic'] = getShowUrl($user_data['head_pic']);
                $resultData['user_name'] = $user_data['user_name'];
                break;
            }
            $jwtService = new JwtServices(['param' => ['user_sn' => $resultData['user_sn'],'be_from'=>$from]]);
            $jwt = $jwtService->issueToken();
            $userModel->where([['user_sn','=',$resultData['user_sn']]])->save(['auth_token'=>$jwt]);
            header('token:'.$jwt);
            $result_code = 200;
            $result_msg = '加载成功';
            (new Lock())->unlock($lock);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            (new Lock())->unlock($lock);
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk app微信登录
     * @method                                      appLogin
     * @param                                       UserModel $userModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-17Tfalse14:false16:false57+080
     */
    public function uniAppLogin(UserModel $userModel, SendMsg $sendMsgServices, UserServices $userServices)
    {
        // 开始执行微信登录
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        Db::startTrans();
        $lock = (new Lock())->lock(["test"], 6000);
        try {
            if (!$lock) {
                throw new \think\Exception("提交过于频繁，请稍后重试", 404);
            }
            $l_user_sn = (isset($param['share_code'])&&$param['share_code']!='') ? base64_decode($param['share_code']) : '';
            $access_token = isset($param['access_token']) ? $param['access_token'] : '';
            $options = [
            'appid' => config('core_config.wechat_app_config.app_id'), // 填写高级调用功能的app id
            'appsecret' => config('core_config.wechat_app_config.app_id'), // 填写高级调用功能的密钥
          ];
            $weObj = new Wechatclass($options);
            if (!$access_token) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $openid = isset($param['openid']) ? $param['openid'] : '';
            $wechat_info = $weObj->getOauthUserinfo($access_token, $openid); //获取用户信息
            if (!$wechat_info || '' == $wechat_info['openid']) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $user_data = [];
            $from = isset($param['from']) ? $param['from'] : 'android'; //
            $deviceid = isset($param['deviceid']) ? $param['deviceid'] : '';
            if ($deviceid != '') {
                switch ($from) {
                case 'android':
                  $user_data['android_device_id'] = $deviceid;
                  break;
                case 'ios':
                  $user_data['ios_device_id'] = $deviceid;
                  break;
              }
            }
            $user_data['wechat_app_openId'] = $wechat_info['openid'];
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $wechat_info['headimgurl'];
            $user_data['unionid'] = isset($wechat_info['unionid']) ? $wechat_info['unionid'] : '';
            $user_data['is_wechat_bind'] = 1;
            $user_info = $userModel
                    ->where([['wechat_app_openId', '=', $wechat_info['openid']]])
                    ->whereOr([['unionid', '=', $wechat_info['unionid']]])
                    ->field('`user_sn`,`wechat_app_openId`,`wechat_applet_openId`,`wechat_openId`,`user_name`,`user_id`,`tel`,`is_bind`,`is_pass_bind`,`head_pic`,`is_all_bind`,`status`,`level`,`l_user_sn`')
                    ->find();
            $is_show = $user_info ? 1 : 0;
            $is_can_push = 0;
            switch ($is_show) {
            case '1':
              if (1 != $user_info['status']) {
                  $resultData['jumpUrl'] = '/pages/login/login';
                  throw new \think\Exception('账户已注销', 404);
              }
              // 存在当前 unionID
              if ($l_user_sn != '' && $user_info['is_all_bind'] == 0 && $l_user_sn != $user_info['user_sn'] && $l_user_sn != $user_info['l_user_sn']) {
                  $l_user_info = $userModel
                                ->where([['user_sn','=',$l_user_sn]])
                                ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                ->find();
                  if ($l_user_info && $l_user_info['status'] == 1) {
                      $user_data['l_user_sn'] = $l_user_info['user_sn'];
                      $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                      $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                      $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                      $is_can_push = 1;
                  }
              }
              $user_res = $userModel
                          ->where([['user_sn', '=', $user_info['user_sn']]])
                          ->save($user_data);
              if ($is_can_push == 1) {
                  // 给上级进行通知 确定是本次绑定上级会员了
                  $content = '尊敬的会员您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                  $push_data = [];
                  $push_data['create_user_sn'] = $user_info['user_sn'];
                  $push_data['user_name'] = $user_info['user_name'];
                  $push_data['time'] = $user_data['bind_time'];
                  $sendMsgServices->sendPushMsg($l_user_sn, '新客户加入通知', $content, 2, $push_data);
                  // 开始同步调整 对应保有等级处理
                  if ($user_info['l_user_sn'] > 0) {
                      // 原来会员的上级存在
                      $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
                  }
                  // 判断游客会员等级的增加
                  $userServices->syncCheckUp($user_info['user_sn'], $l_user_sn, $user_info['user_sn'], $l_user_sn, $user_info['level'], 'chanageUp');
              }
              $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
              $resultData['is_bind'] = $user_info['is_bind'];
              $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
              $resultData['is_wechat_bind'] = 1;
              $resultData['tel'] = $user_info['tel'];
              $resultData['level'] = $user_info['level'];
              $resultData['is_all_bind'] = $user_info['is_all_bind'];
              $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
              $resultData['user_name'] = $user_info['user_name'];
              break;
            case '0':
              $user_data['head_pic'] = $wechat_info['headimgurl'];
              $user_data['user_name'] =  preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
              $user_data['user_sn'] = $userModel->getUserCodeNo(date('Ymd'), 12, 1, 'user_sn');
              $user_data['l_user_sn'] = -1;
              $user_data['l_l_user_sn'] = -1;
              $user_data['l_l_l_user_sn'] = -1;
              $user_data['is_count'] = 1;
              if ($l_user_sn != '') {
                  $l_user_info = $userModel
                                ->where([['user_sn','=',$l_user_sn]])
                                ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                ->find();
                  if ($l_user_info && $l_user_info['status'] == 1) {
                      $user_data['l_user_sn'] = $l_user_info['user_sn'];
                      $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                      $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                      // $user_data['share_time'] = date('Y-m-d H:i:s');
                      $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                      $is_can_push = 1;
                  }
              }
              $user_res = $userModel->create($user_data);
              if ($is_can_push == 1) {
                  // 给上级进行通知 确定是本次绑定上级会员了
                  $content = '尊敬的会员您好，您的好友【'.$user_data['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_data['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                  $push_data = [];
                  $push_data['create_user_sn'] = $user_data['user_sn'];
                  $push_data['user_name'] = $user_data['user_name'];
                  $push_data['time'] = $user_data['bind_time'];
                  $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                  // 判断游客会员等级的增加
                  $userServices->syncCheckUp($user_data['user_sn'], $l_user_sn, $user_data['user_sn'], $l_user_sn, 1, 'chanageUp');
              }
              // 新会员注册完成
              $resultData['user_sn'] = $user_data['user_sn']; // 用户编号
              $resultData['is_bind'] = 0;
              $resultData['is_pass_bind'] = 0;
              $resultData['is_wechat_bind'] = 1;
              $resultData['is_all_bind'] = 0;
              $resultData['tel'] = '';
              $resultData['level'] = 1;
              $resultData['head_pic'] = $user_data['head_pic'];
              $resultData['user_name'] = $user_data['user_name'];
              break;
          }
            $jwtService = new JwtServices(['param' => ['user_sn' => $resultData['user_sn'],'be_from'=>$from]]);
            $jwt = $jwtService->issueToken();
            $userModel->where([['user_sn','=',$resultData['user_sn']]])->save(['auth_token'=>$jwt]);
            header('token:'.$jwt);
            $result_code = 200;
            $result_msg = '加载成功';
            (new Lock())->unlock($lock);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            (new Lock())->unlock($lock);
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk app登录
     * @method                                 appLogin
     * @param                                  UserModel $userModel  [description]
     * @param                                  AliPushMsg $aliPushMsg  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse14:false21:04+080
     */
    public function appLogin(UserModel $userModel, SendMsg $sendMsgServices, UserServices $userServices)
    {
        // 开始执行微信登陆
        $param = request()->param();
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $lock = (new Lock())->lock(["test"], 6000);
        try {
            if (!$lock) {
                throw new \think\Exception("提交过于频繁，请稍后重试", 404);
            }
            $userModel->validate($param, 'appLogin');
            $openId = isset($param['openId']) ? $param['openId'] : '';
            $unionId = isset($param['unionId']) ? $param['unionId'] : '';
            $user_data = [];
            $from = isset($param['from']) ? $param['from'] : 'android'; //
            $deviceid = isset($param['deviceid']) ? $param['deviceid'] : '';
            if ($deviceid != '') {
                switch ($from) {
                case 'android':
                  $user_data['android_device_id'] = $deviceid;
                  break;
                case 'ios':
                  $user_data['ios_device_id'] = $deviceid;
                  break;
              }
            }
            $user_data['wechat_app_openId'] = $openId;
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $param['avatar'];
            $user_data['unionid'] = $unionId;
            $user_data['is_wechat_bind'] = 1;
            $user_info = $userModel
                    ->where([['wechat_app_openId', '=', $openId]])
                    ->whereOr([['unionid', '=', $unionId]])
                    ->field('`user_sn`,`wechat_app_openId`,`wechat_applet_openId`,`wechat_openId`,`user_name`,`user_id`,`tel`,`is_bind`,`is_pass_bind`,`head_pic`,`is_all_bind`,`status`,`level`,`l_user_sn`')
                    ->find();
            $is_show = $user_info ? 1 : 0;
            $is_can_push = 0;
            switch ($is_show) {
              case '1':
                if (1 != $user_info['status']) {
                    $resultData['jumpUrl'] = '/pages/login/login';
                    throw new \think\Exception('账户已注销', 404);
                }
                // 存在当前 unionID
                if ($l_user_sn != '' && $user_info['is_all_bind'] == 0 && $l_user_sn != $user_info['user_sn'] && $l_user_sn != $user_info['l_user_sn']) {
                    $l_user_info = $userModel
                                  ->where([['user_sn','=',$l_user_sn]])
                                  ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                  ->find();
                    if ($l_user_info && $l_user_info['status'] == 1) {
                        $user_data['l_user_sn'] = $l_user_info['user_sn'];
                        $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                        $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                        $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                        $is_can_push = 1;
                    }
                }
                $user_res = $userModel
                            ->where([['unionid', '=', $wechat_info['unionid']]])
                            ->save($user_data);
                if ($is_can_push == 1) {
                    // 给上级进行通知 确定是本次绑定上级会员了
                    $content = '尊敬的会员您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                    $push_data = [];
                    $push_data['create_user_sn'] = $user_info['user_sn'];
                    $push_data['user_name'] = $user_info['user_name'];
                    $push_data['time'] = $user_data['bind_time'];
                    $sendMsgServices->sendPushMsg($l_user_sn, '新客户加入通知', $content, 2, $push_data);
                    // 开始同步调整 对应保有等级处理
                    if ($user_info['l_user_sn'] > 0) {
                        // 原来会员的上级存在
                        $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
                    }
                    // 判断游客会员等级的增加
                    $userServices->syncCheckUp($user_info['user_sn'], $l_user_sn, $user_info['user_sn'], $l_user_sn, $user_info['level'], 'chanageUp');
                }
                $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
                $resultData['is_bind'] = $user_info['is_bind'];
                $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
                $resultData['is_wechat_bind'] = 1;
                $resultData['tel'] = $user_info['tel'];
                $resultData['level'] = $user_info['level'];
                $resultData['is_all_bind'] = $user_info['is_all_bind'];
                $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
                $resultData['user_name'] = $user_info['user_name'];
                break;
              case '0':
                $user_data['head_pic'] = $wechat_info['headimgurl'];
                $user_data['user_name'] =  preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
                $user_data['user_sn'] = $userModel->getUserCodeNo(date('Ymd'), 12, 1, 'user_sn');
                $user_data['l_user_sn'] = -1;
                $user_data['l_l_user_sn'] = -1;
                $user_data['l_l_l_user_sn'] = -1;
                $user_data['is_count'] = 1;
                if ($l_user_sn != '') {
                    $l_user_info = $userModel
                                  ->where([['user_sn','=',$l_user_sn]])
                                  ->field('`user_sn`,`user_id`,`is_check`,`status`,`is_bind`,`l_user_sn`,`l_l_user_sn`')
                                  ->find();
                    if ($l_user_info && $l_user_info['status'] == 1) {
                        $user_data['l_user_sn'] = $l_user_info['user_sn'];
                        $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
                        $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
                        $user_data['bind_time'] = date('Y-m-d H:i:s'); // 代理绑定时间
                        $is_can_push = 1;
                    }
                }
                $user_res = $userModel->create($user_data);
                if ($is_can_push == 1) {
                    // 给上级进行通知 确定是本次绑定上级会员了
                    $content = '尊敬的会员您好，您的好友【'.$user_data['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_data['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
                    $push_data = [];
                    $push_data['create_user_sn'] = $user_data['user_sn'];
                    $push_data['user_name'] = $user_data['user_name'];
                    $push_data['time'] = $user_data['bind_time'];
                    $sendMsgServices->sendPushMsg($user_data['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
                    // 判断游客会员等级的增加
                    $userServices->syncCheckUp($user_data['user_sn'], $l_user_sn, $user_data['user_sn'], $l_user_sn, 1, 'chanageUp');
                }
                $resultData['user_sn'] = $user_data['user_sn']; // 用户编号
                $resultData['is_bind'] = 0;
                $resultData['is_pass_bind'] = 0;
                $resultData['is_wechat_bind'] = 1;
                $resultData['is_all_bind'] = 0;
                $resultData['tel'] = '';
                $resultData['level'] = 1;
                $resultData['head_pic'] = $user_data['head_pic'];
                $resultData['user_name'] = $user_data['user_name'];
                break;
            }
            $jwtService = new JwtServices(['param' => ['user_sn' => $resultData['user_sn'],'be_from'=>$from]]);
            $jwt = $jwtService->issueToken();
            $userModel->where([['user_sn','=',$resultData['user_sn']]])->save(['auth_token'=>$jwt]);
            header('token:'.$jwt);
            $result_code = 200;
            $result_msg = '加载成功';
            (new Lock())->unlock($lock);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            (new Lock())->unlock($lock);
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 绑定手机号
     * @method                                      bindTel
     * @param                                       UserModel $userModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-17Tfalse14:false30:false59+080
     */
    public function bindTel(UserModel $userModel, UserServices $userServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $tel = isset($param['tel']) ? $param['tel'] : '';
            $pass = isset($param['pass']) ? $param['pass'] : '';
            $pass1 = isset($param['pass1']) ? $param['pass1'] : '';
            $captch = isset($param['captch']) ? $param['captch'] : '';
            $l_user_sn = isset($param['l_user_sn']) ? $param['l_user_sn'] : '';
            // 新手机号绑定
            $check_captch_result = $userModel->checkCaptch($param['tel'], 'bind', $param['captch']);
            if (!$check_captch_result) {
                throw new \think\Exception('验证码错误，请重新输入', 404);
            }
            $user_info = $userModel
                    ->where([['user_sn', '=', $user_sn]])
                    ->field('`user_sn`,`user_id`,`head_pic`,`user_name`,`wechat_openId`,`unionid`,`wechat_avatar`,`wechat_nickname`,`is_bind`,`is_wechat_bind`,`is_pass_bind`,`tel`,`is_pass_bind`,`level`')
                    ->find();
            if (!$user_info) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您还没有登录，请先进行登录', 300);
            }
            if (1 == $user_info['is_bind'] && $user_info['is_pass_bind'] == 1) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您已完成手机号&微信的绑定，请直接登录', 300);
            }
            // 开始判断手机号相关的信息
            $tel_info = $userModel
                    ->where([['tel', '=', $tel]])
                    ->field('`user_id`,`user_sn`,`head_pic`,`user_name`,`tel`,`is_bind`')
                    ->find();
            $tel_info = $tel_info ? $tel_info->toArray() : 0;
            if ($tel_info && $tel_info['user_sn'] != $user_sn) {
                throw new \think\Exception("该手机号已经绑定，请更换新手机号", 404);
            }
            $user_data = [];
            $user_data['tel'] = $tel;
            $user_data['pass'] = $pass;
            $user_data['next_pass'] = $pass1;
            $user_data['is_bind'] = 1; // 手机号锁定 密码锁定
            $user_data['is_pass_bind'] = 1; // 密码同时锁定
            $user_res = $userModel
                        ->where([['user_sn', '=', $user_sn]])
                        ->find()
                        ->save($user_data);
            $resultData['user_name'] = $user_info['user_name'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['tel'] = $tel;
            $resultData['is_bind'] = 1;
            $resultData['is_pass_bind'] = 1;
            $resultData['level'] = $user_info['level'];
            $resultData['is_wechat_bind'] = $user_info['is_wechat_bind'];
            $resultData['user_sn'] = $user_info['user_sn'];
            
            if(!empty($l_user_sn)){
               $this->chanageLUserSn($userModel,$userServices); 
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '手机号、密码已经设定，请牢记';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    public function chanageLUserSn(UserModel $userModel, UserServices $userServices)
    {
        // die("asd");
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $param = request()->param();
        $l_user_sn = isset($param['l_user_sn']) ? base64_decode($param['l_user_sn']) : '';
        // $l_user_snse = $param['l_user_sn'];
        // var_dump($l_user_snse);die;
        $user_find = $userModel->where([['user_sn','=',$l_user_sn]])->field('level')->find();//获取用户创建时间 //
        // var_dump($user_find);die;
        if(empty($user_find)){
          throw new \think\Exception("没有此用户", 404);
        }else{
          if($user_find['level']<=1){
           throw new \think\Exception("分享人绑定失败,请重试", 404);
        }  
        }
        
        
            
            // dump($param);die;
            
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            
            $is_all_bind = $userModel->where([['user_sn','=',$user_sn]])->value('is_all_bind');
            $user_time = $userModel->where([['user_sn','=',$user_sn]])->value('create_time');//获取用户创建时间 // 30天内才可以更改
            // var_dump($user_time);die;
            if(time()>strtotime('+30 days', strtotime($user_time))){
                 throw new \think\Exception("您好,您已超过30天不可更改", 404);
            }
            
            $check_now_time = checkNowTime();
            if ($is_all_bind == 0 && $check_now_time == 1) {
               
                $userServices->syncChanageUser($user_sn, $l_user_sn);
            }
         
    
        // $this->result($code, $msg, $result_code, $result_msg,'');
    }
    /**
     * @xk 绑定微信
     * @method                                 bindWechat
     * @param                                  UserModel $userModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse14:false43:05+080
     */
    public function bindWechat(UserModel $userModel)
    {
        // 开始执行微信登录
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        Db::startTrans();
        try {
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel
                    ->where([['user_sn', '=', $user_sn]])
                    ->field('`user_sn`,`user_id`,`head_pic`,`user_name`,`wechat_openId`,`wechat_app_openId`,`unionid`,`is_bind`,`is_bind`,`is_pass_bind`,`is_all_bind`,`level`,`tel`')
                    ->find();
            if (!$user_info) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您还没有登录，请先进行登录', 300);
            }
            if (1 == $user_info['is_wechat_bind']) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您已绑定微信，请重试', 300);
            }
            $wechat_code = isset($param['code']) ? $param['code'] : '';
            $l_user_sn = (isset($param['share_code'])&&$param['share_code']!='') ? base64_decode($param['share_code']) : '';
            $options = [
              'appid' => config('core_config.wechat_config.app_id'), // 填写高级调用功能的app id
              'appsecret' => config('core_config.wechat_config.app_script'), // 填写高级调用功能的密钥
            ];
            $weObj = new Wechatclass($options);
            if ('' == $wechat_code) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $access_token = $weObj->getOauthAccessToken($wechat_code);
            if (!$access_token) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $token = $access_token['access_token'] ? $access_token['access_token'] : '';
            $openid = $access_token['openid'] ? $access_token['openid'] : '';
            $wechat_info = $weObj->getOauthUserinfo($token, $openid); //获取用户信息
            if (!$wechat_info || '' == $wechat_info['openid']) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $user_data = [];
            $user_data['wechat_openId'] = $wechat_info['openid'];
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $wechat_info['headimgurl'];
            $user_data['unionid'] = isset($wechat_info['unionid']) ? $wechat_info['unionid'] : '';
            if ($user_info['wechat_openId'] && $user_info['wechat_openId'] != $wechat_info['openid']) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }
            if ($user_info['unionid'] && $user_info['unionid'] != $wechat_info['unionid']) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }

            $wechat_user_info = $userModel
                      ->where([['wechat_app_openId', '=', $wechat_info['openid']]])
                      ->whereOr([['unionid', '=', $wechat_info['unionid']]])
                      ->field('`is_bind`,`user_sn`,`user_id`,`tel`,`head_pic`,`is_check`')
                      ->find();
            if ($wechat_user_info && $wechat_user_info['user_sn'] != $user_sn) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('当前微信已经绑定过账号，请退出使用微信登录', 300);
            }
            $user_data['is_wechat_bind'] = 1;
            $user_res = $userModel
                        ->where([['user_sn', '=', $user_sn]])
                        ->save($user_data);
            $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
            $resultData['is_wechat_bind'] = 1;
            $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
            $resultData['is_bind'] = $user_info['is_bind'];
            $resultData['is_all_bind'] = $user_info['is_all_bind'];
            $resultData['tel'] = $user_info['tel'];
            $resultData['level'] = $user_info['level'];
            $resultData['is_check'] = $user_info['is_check'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['user_name'] = $user_info['user_name'];
            $result_code = 200;
            $result_msg = '微信授权绑定成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            switch ($e->getCode()) {
              case '300':
                $result_code = $e->getCode();
                break;

              default:
                $result_code = 404;
                break;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 绑定uniapp登录
     * @method                                 bindUniappWechat
     * @param                                  UserModel $userModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-17Tfalse15:06:false59+080
     */
    public function bindUniappWechat(UserModel $userModel)
    {
        // 开始执行微信登录
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        Db::startTrans();
        try {
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel
                  ->where([['user_sn', '=', $user_sn]])
                  ->field('`user_sn`,`user_id`,`head_pic`,`user_name`,`wechat_openId`,`wechat_app_openId`,`unionid`,`is_bind`,`is_bind`,`is_pass_bind`,`is_all_bind`,`tel`,`level`')
                  ->find();
            if (!$user_info) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您还没有登录，请先进行登录', 300);
            }
            if (1 == $user_info['is_wechat_bind']) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您已绑定微信，请重试', 300);
            }
            $access_token = isset($param['access_token']) ? $param['access_token'] : '';
            $options = [
            'appid' => config('core_config.wechat_app_config.app_id'), // 填写高级调用功能的app id
            'appsecret' => config('core_config.wechat_app_config.app_id'), // 填写高级调用功能的密钥
          ];
            $weObj = new Wechatclass($options);
            if (!$access_token) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $openid = isset($param['openid']) ? $param['openid'] : '';
            $wechat_info = $weObj->getOauthUserinfo($access_token, $openid); //获取用户信息
            if (!$wechat_info || '' == $wechat_info['openid']) {
                throw new \think\Exception('请授权微信登录', 404);
            }
            $user_data = [];
            $user_data['wechat_app_openId'] = $wechat_info['openid'];
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $wechat_info['headimgurl'];
            $user_data['unionid'] = isset($wechat_info['unionid']) ? $wechat_info['unionid'] : '';
            if ($user_info['wechat_app_openId'] && $user_info['wechat_app_openId'] != $wechat_info['openid']) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }
            if ($user_info['unionid'] && $user_info['unionid'] != $wechat_info['unionid']) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }

            $wechat_user_info = $userModel
                    ->where([['wechat_app_openId', '=', $wechat_info['openid']]])
                    ->whereOr([['unionid', '=', $wechat_info['unionid']]])
                    ->field('`is_bind`,`user_sn`,`user_id`,`tel`,`head_pic`,`is_check`')
                    ->find();
            if ($wechat_user_info && $wechat_user_info['user_sn'] != $user_sn) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('当前微信已经绑定过账号，请退出使用微信登录', 300);
            }
            $user_data['is_wechat_bind'] = 1;
            $user_res = $userModel
                      ->where([['user_sn', '=', $user_sn]])
                      ->save($user_data);
            $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
            $resultData['is_wechat_bind'] = 1;
            $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
            $resultData['is_bind'] = $user_info['is_bind'];
            $resultData['is_all_bind'] = $user_info['is_all_bind'];
            $resultData['tel'] = $user_info['tel'];
            $resultData['level'] = $user_info['level'];
            $resultData['is_check'] = $user_info['is_check'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['user_name'] = $user_info['user_name'];
            $result_code = 200;
            $result_msg = '微信授权绑定成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk app 绑定微信
     * @method                                      bindAppWechat
     * @param                                       UserModel $userModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-17Tfalse15:false10:false17+080
     */
    public function bindAppWechat(UserModel $userModel)
    {
        // 开始执行微信登陆
        $param = request()->param();
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel
                ->where([['user_sn', '=', $user_sn]])
                ->field('`user_sn`,`user_id`,`head_pic`,`user_name`,`wechat_openId`,`wechat_app_openId`,`unionid`,`is_bind`,`is_bind`,`is_pass_bind`,`is_all_bind`,`tel`,`level`')
                ->find();
            if (!$user_info) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您还没有登录，请先进行登录', 300);
            }
            if (1 == $user_info['is_wechat_bind']) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('您已绑定微信，请重试', 300);
            }
            $userModel->validate($param, 'appLogin');
            $openId = isset($param['openId']) ? $param['openId'] : '';
            $unionId = isset($param['unionId']) ? $param['unionId'] : '';
            $user_data = [];
            $user_data['wechat_app_openId'] = $openId;
            $user_data['wechat_nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $wechat_info['nickname']);
            $user_data['wechat_avatar'] = $param['avatar'];
            $user_data['unionid'] = $unionId;
            if ($user_info['wechat_openId'] && $user_info['wechat_openId'] != $openId) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }
            if ($user_info['unionid'] && $user_info['unionid'] != $unionId) {
                throw new \think\Exception("当前登录微信和系统之前绑定微信不一致，请确认", 404);
            }

            $wechat_user_info = $userModel
                  ->where([['wechat_app_openId', '=', $openId]])
                  ->whereOr([['unionid', '=', $unionId]])
                  ->field('`is_bind`,`user_sn`,`user_id`,`tel`,`head_pic`,`is_check`')
                  ->find();
            if ($wechat_user_info && $wechat_user_info['user_sn'] != $user_sn) {
                $resultData['jumpUrl'] = '/pages/login/login';
                throw new \think\Exception('当前微信已经绑定过账号，请退出使用微信登录', 300);
            }
            $user_data['is_wechat_bind'] = 1;
            $user_res = $userModel
                    ->where([['user_sn', '=', $user_sn]])
                    ->save($user_data);
            $resultData['user_sn'] = $user_info['user_sn']; // 用户编号
            $resultData['is_wechat_bind'] = 1;
            $resultData['is_pass_bind'] = $user_info['is_pass_bind'];
            $resultData['is_bind'] = $user_info['is_bind'];
            $resultData['is_all_bind'] = $user_info['is_all_bind'];
            $resultData['tel'] = $user_info['tel'];
            $resultData['level'] = $user_info['level'];
            $resultData['is_check'] = $user_info['is_check'];
            $resultData['head_pic'] = getShowUrl($user_info['head_pic']);
            $resultData['user_name'] = $user_info['user_name'];
            $result_code = 200;
            $result_msg = '微信授权绑定成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
}
